import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * A Servlet to help view jpg images
 *
 * @author James Chy
 */

public class OneImageUpdate extends PhotoServlet {

    /*
	String oversizeDir;
    String imgmain;
    */
    static final long serialVersionUID = 0;
    
	public void init(ServletConfig config) throws ServletException
	{
		super.init(config);
		/*
		oversize = rb.getString("servletAlbum.oversize");
		imgmain = rb.getString("servletAlbum.imgmain");
		*/
	}

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        response.setContentType("text/html");
        out = response.getWriter();

        String image=request.getParameter("image");        
        String sessionid=request.getParameter("sessionid");        

        out.println("<html>");
        out.println("<body bgcolor=\"white\">");
        out.println("<head>");

		String title = "Image " + image;

		out.println("<title>" + title + "</title>");  
        out.println("</head>");
        out.println("<body>");

        out.println("<TABLE BORDER=1><TR>");

        try
        {
            String query;
            ResultSet rs;
            String image_uid="";
            String description="";
            int count=0;

            // Get image_uid
            query = "SELECT images.uid, images.description FROM images " +
                    "WHERE TRIM(images.image_file) = \"" + image + "\"";
            if(showQuery) out.println("Query: " + query + "<BR>");
            rs = executeQuery(query);
            while(rs.next())
            { 
               image_uid = rs.getString("images.uid");
               description = rs.getString("images.description");
			}

            query = "SELECT session_uid, image_file FROM session_results " +
                    "WHERE session_uid = " + sessionid + " ORDER BY (date) DESC, (image_file) DESC;";
            if(showQuery) out.println("Get session: " + query + "<BR>");
            rs = executeQuery(query);
            while(rs.next())
            {
                if(rs.getString("image_file").equals(image) && !rs.isFirst())
                {
                    rs.previous();
                    String prev=rs.getString("image_file");
                    out.println("<TD VALIGN=TOP>");
                    out.println("<FORM ACTION=OneImageUpdate METHOD=GET>");
                    out.println("<INPUT TYPE=HIDDEN NAME=sessionid VALUE="+sessionid+">");
                    out.println("<INPUT TYPE=HIDDEN NAME=Page VALUE="+request.getParameter("Page")+">");
                    out.println("<INPUT TYPE=HIDDEN NAME=image VALUE=\""+prev+"\">");
                    out.println("<INPUT TYPE=SUBMIT VALUE=Prev>");
                    out.println("</FORM>");
                    out.println("</TD>");
                    rs.next();
                }
                if(rs.getString("image_file").equals(image) && !rs.isAfterLast() && !rs.isLast())
                {
                    rs.next();
                    String next=rs.getString("image_file");
                    out.println("<TD VALIGN=TOP>");
                    out.println("<FORM ACTION=OneImageUpdate METHOD=GET>");
                    out.println("<INPUT TYPE=HIDDEN NAME=sessionid VALUE="+sessionid+">");
                    out.println("<INPUT TYPE=HIDDEN NAME=Page VALUE="+request.getParameter("Page")+">");
                    out.println("<INPUT TYPE=HIDDEN NAME=image VALUE=\""+next+"\">");
                    out.println("<INPUT TYPE=SUBMIT VALUE=Next>");
                    out.println("</FORM>");
                    out.println("</TD>");
                }
            }
                    
            out.println("<TD VALIGN=TOP>");
            out.println("<FORM ACTION=\"SearchResults\" METHOD=\"POST\">");
            out.println("<INPUT TYPE=HIDDEN NAME=sessionid VALUE="+sessionid+">");
            out.println("<INPUT TYPE=HIDDEN NAME=Page VALUE="+request.getParameter("Page")+">");
            out.println("<INPUT TYPE=SUBMIT VALUE=\"Search Results\">");
            out.println("</FORM>");
            out.println("</TD>");

            out.println("<TD VALIGN=TOP>");
            out.println("<FORM ACTION=\"OneImage\" METHOD=\"GET\">");
            out.println("<INPUT TYPE=HIDDEN NAME=sessionid VALUE="+sessionid+">");
            out.println("<INPUT TYPE=HIDDEN NAME=Page VALUE="+request.getParameter("Page")+">");
            out.println("<INPUT TYPE=HIDDEN NAME=\"image\" VALUE=\"" + image + "\">");
            out.println("<INPUT TYPE=HIDDEN NAME=\"image_uid\" VALUE=" + image_uid + ">");
            out.println("<INPUT TYPE=SUBMIT VALUE=\"Read Only\">");
            out.println("</FORM>");
            out.println("</TD>");

            if(showQuery)
               out.println("about to look for "+image+"<BR>");
            String oversizeFileName = oversize+File.separator+image;
            if(showQuery)
               out.println("Filename: "+oversizeFileName+"<BR>");
            File oversizeFile = new File(oversizeFileName);
            if(showQuery)
               out.println("Exists: "+String.valueOf(oversizeFile.exists()));
            if(oversizeFile.exists())
            {
                if(showQuery)
                   out.println("exists<br>");
    
                out.println("<TD VALIGN=TOP>");
                out.println("<FORM ACTION=\"OversizeDisp\" METHOD=\"POST\" TARGET=\"ovr\">");
                out.println("<INPUT TYPE=HIDDEN NAME=\"image\" VALUE=\"" + image + "\">");
                out.println("<INPUT TYPE=SUBMIT VALUE=\"Full Size\">");
                out.println("</FORM>");
            	out.println("</TD>");
            }

            out.println("<TD VALIGN=TOP>");
            out.println("<FORM NAME=\"SavePost\" ACTION=\"OneImageUpdate\" METHOD=\"POST\">");
            out.println("<INPUT TYPE=HIDDEN NAME=\"image\" VALUE=\"" + image + "\">");
            out.println("<INPUT TYPE=HIDDEN NAME=Page VALUE="+request.getParameter("Page")+">");
            out.println("<INPUT TYPE=HIDDEN NAME=\"image_uid\" VALUE=" + image_uid + ">");
            out.println("<INPUT TYPE=HIDDEN NAME=sessionid VALUE="+sessionid+">");
            out.println("<INPUT TYPE=SUBMIT NAME=\"UpdateData\" VALUE=\"Update Data\">");
            out.println("</TD></TR></TABLE>");
            out.println("<TABLE><TR><TD>");

            // Begin Dates
            query = "SELECT COUNT(*) FROM image_date WHERE image_date.image_uid = " + image_uid;
            
            if(showQuery)
                out.println("Query:<BR>" + query + "<BR>");

            rs = executeQuery(query);

            rs.next();
            count = rs.getInt("count(*)");

            query = "SELECT dates.uid, dates.date, image_date.image_uid " +
                    "FROM dates " +
                    "LEFT OUTER JOIN image_date " +
                    "ON dates.uid = image_date.date_uid " +
                    "AND image_date.image_uid = " + image_uid + " " +
                    "ORDER BY dates.date DESC";
            rs = executeQuery(query);
            
            if(showQuery)
                out.println("Query:<BR>" + query + "<BR>");
            out.println("<B><A HREF=\"MaintainDates\" TARGET=\"_blank\">Dates</A></B><BR>");
            out.println("<SELECT NAME=\"dates\" SIZE=\"5\">");

            if(count==0)
                out.println("<OPTION SELECTED VALUE=\"0\">&lt;None&gt;");
            else
                out.println("<OPTION VALUE=\"0\">&lt;None&gt;");

            while (rs.next()) 
            {
                String date_uid = rs.getString("dates.uid");
                String date = rs.getString("dates.date");   
                String outer = rs.getString("image_date.image_uid"); 
                out.print("<OPTION ");
                if(outer!=null)
                    out.print("SELECTED ");
                out.println("VALUE=\"" + date_uid + "\">" + OneImageUpdate.MonthDayYear(date));
            }
            out.println("</SELECT>");
            // End Dates

            out.println("</TD><TD>");

            // Begin People
            query = "SELECT COUNT(*) FROM image_person WHERE image_person.image_uid = " + image_uid;
            
            if(showQuery)
                out.println("Query:<BR>" + query + "<BR>");

            rs = executeQuery(query);

            rs.next();
            count = rs.getInt("count(*)");

            query = "SELECT people.*," +
                    " image_person.image_uid, (image_person.image_uid is null) a " +
                    "FROM people " +
                    "LEFT OUTER JOIN image_person " +
                    "ON people.uid = image_person.person_uid " +
                    "AND image_person.image_uid = " + image_uid + " " +
                    "ORDER BY a, people.lastName, people.firstName, people.middleName";
            
            if(showQuery)
                out.println("Query:<BR>" + query + "<BR>");

            rs = executeQuery(query);

            out.println("<B><A HREF=\"MaintainPeople\" TARGET=\"_blank\">People</A></B><BR>");
            out.println("<SELECT NAME=\"people\" SIZE=\"5\" MULTIPLE>");

            if(count==0)
                out.println("<OPTION SELECTED VALUE=\"0\">&lt;None&gt;");
            else
                out.println("<OPTION VALUE=\"0\">&lt;None&gt;");

            while (rs.next()) 
            {
                String person_uid = rs.getString("people.uid");
                String name=OneImageUpdate.FirstNameLastName(rs);
                String outer = rs.getString("image_person.image_uid"); 
                out.print("<OPTION ");
                if(outer!=null)
                    out.print("SELECTED ");
                out.println("VALUE=\"" + person_uid + "\">" + name);
            }
            out.println("</SELECT>");
            // End People

            out.println("</TD><TD>");

            // Begin Things
            query = "SELECT COUNT(*) FROM image_thing WHERE image_thing.image_uid = " + image_uid;
            
            if(showQuery)
                out.println("Query:<BR>" + query + "<BR>");

            rs = executeQuery(query);

            rs.next();
            count = rs.getInt("count(*)");

            query = "SELECT things.uid, things.thing, " +
                    " image_thing.image_uid, " +
                    " (image_thing.image_uid is null) a " +
                    "FROM things " +
                    "LEFT OUTER JOIN image_thing " +
                    "ON things.uid = image_thing.thing_uid " +
                    "AND image_thing.image_uid = " + image_uid + " " +
                    "ORDER BY a, things.thing";
            
            if(showQuery)
                out.println("Query:<BR>" + query + "<BR>");

            rs = executeQuery(query);

            out.println("<B><A HREF=\"MaintainThings\" TARGET=\"_blank\">Things</A></B><BR>");
            out.println("<SELECT NAME=\"things\" SIZE=\"5\" MULTIPLE>");

            if(count==0)
                out.println("<OPTION SELECTED VALUE=\"0\">&lt;None&gt;");
            else
                out.println("<OPTION VALUE=\"0\">&lt;None&gt;");

            while (rs.next()) 
            {
                String thing_uid = rs.getString("things.uid");
                String thing = rs.getString("things.thing");    
                String outer = rs.getString("image_thing.image_uid"); 
                out.print("<OPTION ");
                if(outer!=null)
                    out.print("SELECTED ");
                out.println("VALUE=\"" + thing_uid + "\">" + thing);
            }
            out.println("</SELECT>");
            // End Things

            out.println("</TD><TD>");

            // Begin Places
            query = "SELECT COUNT(*) FROM image_place WHERE image_place.image_uid = " + image_uid;
            
            if(showQuery)
                out.println("Query:<BR>" + query + "<BR>");

            rs = executeQuery(query);

            rs.next();
            count = rs.getInt("count(*)");

            query = "SELECT places.uid, places.place, " +
                    " image_place.image_uid, " +
                    " (image_place.image_uid is null) a " +
                    "FROM places " +
                    "LEFT OUTER JOIN image_place " +
                    "ON places.uid = image_place.place_uid " +
                    "AND image_place.image_uid = " + image_uid + " " +
                    "ORDER BY a, places.place";
            
            if(showQuery)
                out.println("Query:<BR>" + query + "<BR>");

            rs = executeQuery(query);

            out.println("<B><A HREF=\"MaintainPlaces\" TARGET=\"_blank\">Places</A></B><BR>");
            out.println("<SELECT NAME=\"places\" SIZE=\"5\" MULTIPLE>");

            if(count==0)
                out.println("<OPTION SELECTED VALUE=\"0\">&lt;None&gt;");
            else
                out.println("<OPTION VALUE=\"0\">&lt;None&gt;");

            while (rs.next()) 
            {
                String place_uid = rs.getString("places.uid");
                String place = rs.getString("places.place");    
                String outer = rs.getString("image_place.image_uid"); 
                out.print("<OPTION ");
                if(outer!=null)
                    out.print("SELECTED ");
                out.println("VALUE=\"" + place_uid + "\">" + place);
            }
            out.println("</SELECT>");
            // End Places

            out.println("</TD></TR></TABLE>");

            out.println("<BR>");
            out.println("<IMAGE SRC=\"" + imgmain + "/" + image + "\"><BR>");
			out.println("<TEXTAREA NAME=\"description\" COLS=\"60\" ROWS=\"3\">" + description + "</TEXTAREA>");
			out.println("</FORM>");
        }
        catch(SQLException sqle)
        {
            out.println("SQL Exception");
        }
        
        out.println("</body>");
        out.println("</html>");

    }
    public void doPost(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        response.setContentType("text/html");
        out = response.getWriter();
        

        out.println("<html>");
        out.println("<body bgcolor=\"white\">");
        out.println("<head>");

		out.println("<title>Post</title>");  
        out.println("</head>");
        out.println("<body>");


        if(showQuery)
        {
            for(Enumeration e=request.getParameterNames(); e.hasMoreElements(); )
            {
                String currentElement=e.nextElement().toString();
                String currentValues[]=request.getParameterValues(currentElement);
                for(int i=0; i<currentValues.length; i++)
                    out.println(currentElement + "[" + i + "]=" + 
                            currentValues[i] + "<BR>");
            }
            out.println("Description: " + request.getParameter("description") + "<BR>");
        }

        String query;

        String image_uid = request.getParameter("image_uid");

        // Begin People
        query = "DELETE FROM image_person " +
                "WHERE image_uid = " + image_uid;

        if(showQuery)
            out.println(query + "<BR>");

        int count = executeUpdate(query);
        
        String peopleValues[]=request.getParameterValues("people");
        for(int i=0; i<peopleValues.length; i++)
        {
            if(!peopleValues[i].equals("0"))
            {
                query = "INSERT INTO image_person " +
                        "SET image_uid = " + image_uid + "," +
                        "person_uid = " + peopleValues[i];
                if(showQuery)
                    out.println(query + "<BR>");
                count = executeUpdate(query);
            }
        }
        // End People

        // Begin Places
        query = "DELETE FROM image_place " +
                "WHERE image_uid = " + image_uid;

        if(showQuery)
            out.println(query + "<BR>");

        count = executeUpdate(query);
        
        String placeValues[]=request.getParameterValues("places");
        for(int i=0; i<placeValues.length; i++)
        {
            if(!placeValues[i].equals("0"))
            {
                query = "INSERT INTO image_place " +
                        "SET image_uid = " + image_uid + "," +
                        "place_uid = " + placeValues[i];
                if(showQuery)
                    out.println(query + "<BR>");
                count = executeUpdate(query);
            }
        }
        // End Places

        // Begin Dates
        query = "DELETE FROM image_date " +
                "WHERE image_uid = " + image_uid;

        if(showQuery)
            out.println(query + "<BR>");

        count = executeUpdate(query);
        
        String dateValues[]=request.getParameterValues("dates");
        for(int i=0; i<dateValues.length; i++)
        {
            if(!dateValues[i].equals("0"))
            {
                query = "INSERT INTO image_date " +
                        "SET image_uid = " + image_uid + "," +
                        "date_uid = " + dateValues[i];
                if(showQuery)
                    out.println(query + "<BR>");
                count = executeUpdate(query);
            }
        }
        // End Dates

        // Begin Things
        query = "DELETE FROM image_thing " +
                "WHERE image_uid = " + image_uid;

        if(showQuery)
            out.println(query + "<BR>");

        count = executeUpdate(query);
        
        String thingValues[]=request.getParameterValues("things");
        for(int i=0; i<thingValues.length; i++)
        {
            if(!thingValues[i].equals("0"))
            {
                query = "INSERT INTO image_thing " +
                        "SET image_uid = " + image_uid + "," +
                        "thing_uid = " + thingValues[i];
                if(showQuery)
                    out.println(query + "<BR>");
                count = executeUpdate(query);
            }
        }
        // End Things

        // Begin Description
        String description=request.getParameter("description");
        query = "UPDATE images " +
                "SET description = \"" + description + "\" " +
                "WHERE uid = " + image_uid;

        if(showQuery)
            out.println(query + "<BR>");

        count = executeUpdate(query);
        // End Description

        out.println("<H1>Data Saved, updated " + String.valueOf(count) + " </H1>");
        out.println("<FORM ACTION=OneImageUpdate METHOD=GET>");
        out.println("<INPUT TYPE=SUBMIT VALUE=\"Return to Image\">");
        out.println("<INPUT TYPE=HIDDEN NAME=image VALUE=\""+request.getParameter("image")+"\">");
        out.println("<INPUT TYPE=HIDDEN NAME=Page VALUE="+request.getParameter("Page")+">");
        out.println("<INPUT TYPE=HIDDEN NAME=sessionid VALUE=\""+request.getParameter("sessionid")+"\">");
            out.println("</FORM>");
            

        out.println("</BODY></HTML>");
    }
               
}



